<?php

namespace app\wx\service;
use think\Db;
use Exception;
use encryption\encryption;
use app\wx\service\AdminTokenService;
use app\common\cache\RedisPublic;
use think\facade\Config;

/**
 * 管理员表操作数据库
 */
class AdminLoginService
{
    /**
     * @param array $param  参数
     * 
     * @return array
     */
    static public function login($param)
    {
        //查询用户名
        $userInfo = Db::name('admin')->where('number',$param['number'])->field('id,salt,pwd,number,status,name')->find();
        if(empty($userInfo))
            error('用户名不存在');
        //判断密码
        if(encryption::enMd5($param['pwd'],$userInfo['salt']) !== $userInfo['pwd'])
            error('用户密码错误');
        //判断状态
        if($userInfo['status'] !== 1)
            error('用户名被禁用');
        //登录成功，生成token
        $tokenData = [
            'id'         => $userInfo['id'],
            'login_time' => date("Y-m-d H:i:s"),
            'login_ip'   => $param['request_ip']
        ];
        $token = AdminTokenService::create($tokenData);
        //存储到缓存
        RedisPublic::setRedisTable('login')->set($userInfo['id'],[
            'token'    => $token,
            'userInfo' => $userInfo,
            'time'     => time(),
            'date'     => date('Y-m-d H:i:s')
        ],Config::get('admin.login_exp'));
        //登录返回
        return [
            'token' => $token,
            'userInfo'   => [
                'id'     => $userInfo['id'],
                'name'   => $userInfo['name'],
                'number' => $userInfo['number']
            ]
        ];
    }
}